﻿using _8Group.MES.MengIService;
using _8Group.MES.MengIService.DTO;
using _8Group.MES.Model.WM仓储管理;
using FourGroups.Project;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace _8Group.MES.MengService
{
    [ApiExplorerSettings(GroupName = "孟祥宇")]
    public class WmTransferService : ApplicationService, IWmTransferService
    {
        private readonly IRepository<WM_Transfer, int> _wmTransferRepository;
        public WmTransferService(IRepository<WM_Transfer, int> wmTransferRepository)
        {
            _wmTransferRepository = wmTransferRepository;
        }

        public async Task<string> GetTransferAsync(string? transferCode, string? transferName, string? transferType, string? fromWarehouseName, string? toWarehouseName, int page, int limit)
        {
            var stock = await _wmTransferRepository.GetQueryableAsync();

            stock = stock.WhereIf(!string.IsNullOrEmpty(transferCode), x => x.TransferCode.Contains(transferCode));
            stock = stock.WhereIf(!string.IsNullOrEmpty(transferName), x => x.TransferName.Contains(transferName));
            stock = stock.WhereIf(!string.IsNullOrEmpty(transferType), x => x.TransferType.Contains(transferType));
            stock = stock.WhereIf(!string.IsNullOrEmpty(fromWarehouseName), x => x.FromWarehouseName.Contains(fromWarehouseName));
            stock = stock.WhereIf(!string.IsNullOrEmpty(toWarehouseName), x => x.ToWarehouseName.Contains(toWarehouseName));

            int totalCount = stock.Count();

            stock = stock.OrderByDescending(c => c.Id).Skip((page - 1) * limit).Take(limit);

            return JsonConvert.SerializeObject(new { code = "0", data = stock.ToList(), count = totalCount, msg = "success" }, Formatting.Indented);
        }

        public async Task<int> AddTransferAsync(WmTransferDTO WmTransfer)
        {
            var n = AutoMapperExt.MapTo<WM_Transfer>(WmTransfer);
            await _wmTransferRepository.InsertAsync(n);
            return 1;
        }

        public async Task<int> UpdateTransferAsync(UpdateWmTransferDTO WmTransfer)
        {
            var model = AutoMapperExt.MapTo<WM_Transfer>(WmTransfer);
            await _wmTransferRepository.UpdateAsync(model);
            return 1;

        }

        public async Task<int> DeleteTransferAsync(int id)
        {
            await _wmTransferRepository.DeleteAsync(id, true);
            return 1;
        }

    }
}
